﻿using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Text;

namespace TCG
{

	/// <summary>
	/// 编辑器脚本
	/// </summary>
	public static class GameEditorTools 
	{
		/// <summary>
		/// 获取发布资源的目标平台.
		/// </summary>
		
	    public static BuildTarget GetBuildTarget ()
		{
	        #if UNITY_IPHONE
			return BuildTarget.iPhone;
	        #elif UNITY_ANDROID
			return BuildTarget.Android;
	        #elif UNITY_EDITOR_WIN
			return BuildTarget.StandaloneWindows;
	        #elif UNITY_EDITOR_OSX
	        return BuildTarget.StandaloneOSXUniversal;
	        #endif
		}

		/// <summary>
		/// 游戏中所有可序列化的资源都应该位于该文件夹下
		/// </summary>
		
	    public static string SerializableSourceDir = "Assets/Serializable/";

		public static string SerializableDirName = "Serializable";

		/// <summary>
	    /// 检查<paramref name="sourceObject"/>是不是在可序列化的目录下，如果是则返回相对于
	    /// 序列化顶级目录的相对路径，否则返回null
		/// </summary>
		
	    public static string GetRelativeAssetPath (UnityEngine.Object sourceObject)
		{
			string sourcePath = AssetDatabase.GetAssetPath (sourceObject);
			if (sourcePath == null) return null;

			int i = sourcePath.IndexOf (SerializableSourceDir);
			if (i == -1)
			{
				return null;
			}

			return sourcePath.Substring (i + SerializableSourceDir.Length);
		}

		public static string GetRelativeAssetPathNoSuffix (UnityEngine.Object sourceObject)
		{
			string result = GetRelativeAssetPath (sourceObject);
			if (string.IsNullOrEmpty (result))
			{
				return result;
			}
			else
			{
				int suffixIndex = result.LastIndexOf (".");
				if (suffixIndex != -1)
				{
					result = result.Substring (0, suffixIndex);
				}
				return result;
			}
		}


		public static string GetPathForSerilize (UnityEngine.Object sourceObject)
		{
			string sourcePath = GetRelativeAssetPathNoSuffix (sourceObject);
			if (sourcePath == null) return null;

			string streamingPath = CommonTools.GetStreamingPath (sourcePath);
			FileInfo fi = new FileInfo (streamingPath);
			if (!fi.Directory.Exists)
			{
				fi.Directory.Create ();
			}
			return streamingPath;
		}

		/// <summary>
		/// 获取Assets/{relativePath}下所有类型为T的资源.
		/// </summary>
		public static List<T> CollectAll<T>(string relativePath) where T : UnityEngine.Object
		{
			string path = Path.Combine (Application.dataPath, relativePath);
			List<T> l = new List<T>();
			try
			{
				string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
				foreach (string file in files)
				{
					if (file.Contains(".meta") || file.Contains (".svn")) continue;
					
					string assetPath = "Assets" + file.Replace (Application.dataPath, "");
					T asset = (T) AssetDatabase.LoadAssetAtPath(assetPath, typeof(T));
					if (asset == null) continue;
					l.Add(asset);
				}
			}
			catch (DirectoryNotFoundException)
			{
				Debug.Log (string.Format ("\nDirectory {0} not found.", path));
			}
			return l;
		}
		
		/// <summary>
		/// 创建xml文档，并附加根节点。使用utf-8编码。
		/// </summary>
		
		public static XmlDocument CreateXmlWithRoot (string rootName = "root")
		{
			XmlDocument xmlDoc = new XmlDocument ();
			XmlDeclaration dec = xmlDoc.CreateXmlDeclaration ("1.0", "utf-8", "yes");
			xmlDoc.AppendChild (dec);
			xmlDoc.AppendChild (xmlDoc.CreateElement (rootName));
			return xmlDoc;
		}
		
		/// <summary>
		/// 为xml文档中的节点添加属性值。
		/// </summary>
		
		public static void CreateAttribute (XmlNode hostNode, string attName, string attValue)
		{
			XmlDocument xmlDoc = hostNode.OwnerDocument;
			XmlAttribute att = xmlDoc.CreateAttribute (attName);
			att.Value = attValue;
			hostNode.Attributes.Append (att);
		}
		
		/// <summary>
		/// 将xmlDoc写入filePath指向的文件中，使用utf-8编码。
		/// </summary>
		
		public static void WriteXMLFile (XmlDocument xmlDoc, string filePath)
		{
			string dirpath = Path.GetDirectoryName (filePath);
			if (!Directory.Exists (dirpath))
			{
				Directory.CreateDirectory (dirpath);
			}
			
			XmlTextWriter tw = new XmlTextWriter (filePath, new UTF8Encoding (false));
			xmlDoc.Save (tw);
			tw.Close ();
		}
	}
}
